import React, { useEffect, useState } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import TitleBar from '@/src/components/titleBar';
import './index.less';
import { Button, Image, Text, View } from '@tarojs/components';
import store from '@/src/store';
import CommonModal from '@/src/components/commonModal';
import { AtInput } from 'taro-ui';
import { showToast, StatusToast } from '@/src/components/statusToast';
import { observer } from 'mobx-react-lite';
import {
  signoutFun,
  updateBasicInfoFun,
  userInfoFun,
} from '@/src/common/method/loginFun';
import { updateInfoFun } from '@/src/common/method/userInfoFun';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { getNetWorkStatus } from '@/src/common/util/util';

//退出账号
const ExitAccount = () => {
  const [nickname, setNickName] = useState(''); //用户昵称
  const [showNickModal, setShowNickModal] = useState(false); //修改昵称弹框
  const [title, setTitle] = useState<string>('修改昵称');
  const [exitConfirm, setExitConfirm] = useState(false);
  const [data, setData] = useState<any>([]);
  const [avatarUrl, setAvatarUrl] = useState<any>(''); //头像
  const [userId, setUserId] = useState<any>(''); //用户id
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  const getUserInfo = () => {
    const userId = Taro.getStorageSync('userId');
    userInfoFun({
      access_token: Taro.getStorageSync('access_token_login'),
    }).then((res: any) => {
      setData(res);
      setNickName(Taro.getStorageSync(`nickname-${userId}`));
      setAvatarUrl(
        res.avatarUrl
          ? res.avatarUrl
          : 'https://file.linkcook.cn/image/wineMiniProgram/home/portrait.png'
      );
      setUserId(res.userId);
    });
  };

  useEffect(() => {
    getUserInfo();
  }, []);

  //退出按钮
  const handleExitClick = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setExitConfirm(true);
    setShowNickModal(true);
    setTitle('确定要退出当前账号吗?');
    //
  };
  //更新用户信息
  const updateUserInfo = (avatarUrl: any, nickname?: any) => {
    const userId = Taro.getStorageSync('userId');
    //登录成功后，刷新用户信息
    updateInfoFun({
      ucUserId: Taro.getStorageSync('userId'),
      ucLoginPhone: Taro.getStorageSync('mobile'),
      ucNickname: nickname
        ? nickname
        : Taro.getStorageSync(`nickname-${userId}`),
      ucAvatarUrl: avatarUrl,
      address: store.commonStore.province,
    }).then((res: any) => {
      console.log(res, '更新用户信息====111');
      //更新一次后不再需要更新，退出后需要再次更新
      store.commonStore.setNeedUpdateInfo(false);
    });
  };

  //修改图像
  const handleChange = async () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    const res = await Taro.chooseImage({ count: 1, sourceType: ['album'] });
    const token: any = Taro.getStorageSync('access_token_login');
    const tempFilePaths = res.tempFilePaths;
    //头像上传--测试环境
    Taro.uploadFile({
      url: 'https://account-api.haier.net/v2/user/avatar/upload', // 生产环境
      // url: 'https://testaccount.haier.com/v2/user/avatar/upload', // 测试环境
      header: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}`,
      },
      filePath: tempFilePaths[0],
      name: 'file',
      success(res) {
        console.log(res, '更新头像=====');
        const data: any = JSON.parse(res.data);
        if (data.error && data.error === 'change_avatar_too_often') {
          Taro.showToast({
            title: '更新头像太频繁，请稍后重试！',
            icon: 'none',
          });
          return;
        } else if (data.error && data.error === 'upload.file.illegal') {
          Taro.showToast({
            title: '无法识别该图片，请重新选择！',
            icon: 'none',
          });
          return;
        }
        if (data.avatarUrl) {
          setAvatarUrl(data.avatarUrl);
          store.commonStore.setNeedRefresh(true);
          //更新用户信息-头像
          updateUserInfo(data.avatarUrl);
        } else {
          Taro.showToast({ title: '更新头像失败', icon: 'none' });
        }
      },
      fail(res) {
        Taro.showToast({ title: '更新头像失败', icon: 'none' });
        console.log(res, '上传失败');
      },
    });
  };
  //修改昵称
  const handleChangeNickName = (val: any) => {
    const userId = Taro.getStorageSync('userId');
    const filteredValue = val.slice(0,10).replace(
      /[^\u4e00-\u9fa5a-zA-Z0-9\s,.;:!?~，。；：！？～、（）()【】\[\]{}“”‘’'`…\-=*\/@#%^&+_|\\]/g,
      ''
    );
    //只能输入10个以内的中文
    if (val.trim().length > 10) {
      console.log(val,'val===========');
      showToast('昵称最多输入10个字符', 'error', 3);
      return;
    } else if (filteredValue === val) {
      Taro.setStorageSync(`nickname-${userId}`, val);
      setNickName(val.trim());
    } else {
      showToast('请输入正确的昵称', 'error', 3);
    }
  };

  //提交修改
  const handleSubmit = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (exitConfirm) {
      //调用更新基本信息接口
      setShowNickModal(false);
      signoutFun({
        access_token: Taro.getStorageSync('access_token_login'),
      }).then((res: any) => {
        Taro.clearStorageSync();
        //退出后需要更新用户信息
        store.commonStore.setNeedUpdateInfo(true);
        // Taro.setStorageSync('loginOut', '1');
        // Taro.navigateTo({ url: '/subPagesAuth/login/index' });
        Taro.reLaunch({ url: '/pages/home/index' });
      });
    } else if (nickname.trim().length > 0) {
      //调用更新基本信息接口
      setShowNickModal(false);
      updateBasicInfoFun({
        access_token: store.commonStore.accessToken,
        userId: userId,
        nickname: nickname,
      })
        .then((res: any) => {
          console.log(res,'更新昵称接口====');
          if (res.success) {
            store.commonStore.setNeedRefresh(true);
          } else {
            showToast('更新昵称失败', 'error', 3);
          }
          //更新用户信息
          updateUserInfo(avatarUrl, nickname);
        })
        .catch((e: any) => {
          showToast('更新昵称失败', 'error', 3);
        });
    } else {
      showToast('请输入昵称', 'error', 3);
    }
  };

  const handleNickClick = () => {
    setShowNickModal(true);
    setExitConfirm(false);
  };

  //修改昵称内容
  const content = () => {
    return (
      <View>
        <AtInput
          className="exit-account-input"
          placeholder="请输入昵称"
          type="text"
          value={nickname.slice(0,10)}
          onChange={(e) => handleChangeNickName(e)}
          title=""
          name={''}
        />
      </View>
    );
  };

  return (
    <View
      className="exit-account-container"
      style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title="个人中心" />
      <View
        className="exit-account-content"
        style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
      >
        <View className="exit-account-item">
          <View>头像</View>
          <View onClick={() => handleChange()}>
            <Image className="exit-account-avatar" src={avatarUrl} />
            <Image
              className="more"
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/mine/arrow.png'
              }
            />
          </View>
        </View>
        <View className="exit-account-item">
          <View>昵称</View>
          <View onClick={() => handleNickClick()}>
            <Text>{nickname.slice(0,10)}</Text>
            <Image
              className="more"
              src={
                'https://file.linkcook.cn/image/wineMiniProgram/mine/arrow.png'
              }
            />
          </View>
        </View>
        <View className="exit-account-item">
          <View>手机号</View>
          <View>{data.mobile}</View>
        </View>
        <View className="exit-account-item">
          <View>账号</View>
          <View>{data.userId}</View>
        </View>
      </View>
      <Button className="exit-btn" onClick={() => handleExitClick()}>
        退出登录
      </Button>
      <CommonModal
        visible={showNickModal}
        title={title}
        okText={exitConfirm ? '确定' : '提交'}
        content={exitConfirm ? '' : content()}
        okClick={() => handleSubmit()}
        cancelText={'取消'}
        cancelClick={() => setShowNickModal(false)}
      />
      <StatusToast />
    </View>
  );
};

export default observer(ExitAccount);
